<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\OceanEnum;
use app\model\AccountDailyStatModel;
use app\model\CrontabTaskModel;
use app\service\CrontabTaskService;
use app\service\stat\daily\ProductAccountTypeService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class ProductAccountTypeDailyStatWork extends BaseWork implements DailyStatWork
{
    public string $tag;

    public array $clientAccountInfo = [];

    /**
     * 设置任务标识.
     * @param mixed $tag
     */
    public function setTag($tag = ''): bool
    {
        if (! is_null($tag)) {
            $this->tag = strval($tag);
        }
        return true;
    }

    /**
     * 获取任务标识.
     */
    public function getTag(): string
    {
        return $this->tag;
    }

    /**
     * 获取脚本名.
     */
    public function getCommandName(): string
    {
        return $this->getName();
    }

    /**
     * 获取定时任务.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getCrontabTaskInfo(): CrontabTaskModel
    {
        $where = [
            ['task_name', '=', $this->getName()],
            ['tag', '=', $this->getTag()],
        ];

        $obj = new CrontabTaskModel();
        $model = $obj->where($where)->field(true)->find();
        return $model instanceof CrontabTaskModel ? $model : $obj;
    }

    protected function configure()
    {
        // 指令配置
        $this->setName('product_account_type_daily_stat_work');
        $this->setDescription('产品分帐户类型流水汇总');
        $this->addArgument('type', Argument::REQUIRED, '类型  1：昨日报表 2：自定义时间');
        $this->addArgument('media_id', Argument::OPTIONAL, '媒体id');
        $this->addArgument('start_date', Argument::OPTIONAL, '开始日期');
        $this->addArgument('end_date', Argument::OPTIONAL, '结束日期');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');

        $output->writeln('=======流水汇总开始' . date('Y-m-d H:i:s', time()) . '=======');
        $type = $input->getArgument('type');
        $mediaId = intval($input->getArgument('media_id'));
        $this->setTag($mediaId);
        $startDate = $input->getArgument('start_date');
        $endDate = $input->getArgument('end_date');
        // 默认昨日
        if ($type == OceanEnum::YESTERDAY) {
            // 获取凌晨的时间戳
            $time = strtotime(date('Y-m-d 00:00:00'));
            // 如果已执行，就不跑了
            //            if ($this->getCrontabTaskInfo()->finish_time > $time) {
            //                exit;
            //            }
            $keyWord = 'account_daily_stat_work';
            $isOk = CrontabTaskModel::where('task_name', $keyWord)
                ->where('tag', $mediaId)
                ->where('finish_time', '>', $time)
                ->find();
            if (! $isOk) {
                exit;
            }
        }
        if ($type == OceanEnum::YESTERDAY) {
            $yesterDay = date('Ymd', strtotime('-1 day'));
            $startDate = $yesterDay;
            $endDate = $yesterDay;
        } elseif ($type == OceanEnum::CUSTOM_DAY) {
            if (! $startDate || ! $endDate) {
                $output->writeln('===========开始时间，结束时间都必须存在！===========');
                return;
            }

            if ($startDate > $endDate) {
                $output->writeln('===========开始时间必须小于结束时间！===========');
                return;
            }
        } elseif ($type == 3) {
            // 三天前，前天
            $yesterDay = date('Ymd', strtotime('-3 day'));
            $startDate = $yesterDay;
            $endDate = $yesterDay;
        }
        $productService = new ProductAccountTypeService();
        $dataList = self::getStatList(intval($startDate), intval($endDate), $mediaId);
        if ($dataList) {
            try {
                foreach ($dataList as $data) {
                    $productService->setData($data);
                    $res = $productService->saveStatData();
                    if (! $res) {
                        $output->writeln('===========失败:' . $productService->getError(0) . '===========');
                    }
                }
                if ($type == 1) {
                    // 更新任务状态
                    CrontabTaskService::setSingleTask($this);
                }
            } catch (Exception $e) {
                dump($e);
            }
        }
        $output->writeln('=======流水汇总结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    /**
     * 获取指定流水数据.
     */
    private function getStatList(int $startDate, int $endDate, int $mediaId = 0)
    {
        $where[] = [
            ['id', '>', 0],
            ['stat_date', '>=', $startDate],
            ['stat_date', '<=', $endDate],
        ];
        if ($mediaId) {
            $where[] = ['media_id', '=', $mediaId];
        }
        return AccountDailyStatModel::where($where)
            ->group('product_id,account_type,media_id,stat_date')
            ->field('product_id,client_id,account_type,media_id,stat_date,sum(cost) as cost,sum(cash_cost) as cash_cost,sum(reward_cost) as reward_cost,sum(balance) as balance')
            ->select();
    }
}
